import { ref } from 'vue'

import { catchFn } from '@/libs/common'
import { addFriendGroup, deleteFriend, getFriendGroupList, getFriendList } from './api'
import { topMessage } from '@/components/TopMessage/data'
import { curFriend } from '@/pages/user/edit-info/data'

/** 好友群组列表 */
const groupList = ref<T_FriendGroup[]>([])
/** 好友群组列表 */
const groupMap = ref<{ [key: string | number]: string }>({})
/** 当前选择群组序号 */
const curGroupIdx = ref(-1)
/** 好友列表 */
const friends = ref<T_Friend[]>([])
/** 当前选择好友序号 */
const curFriendIdx = ref(-1)

let page = 1
const size = 10000
const searchKey = ref('')

export { groupList, groupMap, curGroupIdx, friends, curFriendIdx, searchKey }

/**
 * 更新好友分组列表
 */
const updateFriendGroup = async () => {
  const { data } = await getFriendGroupList()

  groupList.value = data
  data.length && (curGroupIdx.value = 0)

  for (const item of data) {
    groupMap.value[item.id] = item.groupName
  }
}

/**
 * 更新好友列表
 */
const updateFriend = async () => {
  const group = groupList.value[curGroupIdx.value]

  if (!group) return

  const { data } = await getFriendList(page, size, group.id, searchKey.value)

  friends.value = data.list
  curFriendIdx.value = -1
}

/**
 * 初始化
 */
const init = () =>
  catchFn(async () => {
    await updateFriendGroup()
    await updateFriend()
  })

/**
 * 新增好友分组
 */
const newGroup = () =>
  catchFn(async () => {
    await addFriendGroup('Test Group')
    await updateFriendGroup()

    curGroupIdx.value = groupList.value.length - 1
    page = 1

    await updateFriend()

    topMessage.success('新增成功')
  })

/**
 * 删除好友
 */
const removeFriend = () =>
  catchFn(async () => {
    const f = friends.value[curFriendIdx.value]

    if (!f) throw '请选择好友'

    // 删除确认
    const confirm = await new Promise(resolve => {
      uni.showModal({
        title: '提示',
        content: `确认删除“${f.nickname}”吗`,
        success: res => resolve(res.confirm),
      })
    })

    if (!confirm) return

    await deleteFriend(f.id)
    await updateFriend()
  })

/**
 * 选择好友分组
 * @param idx 分组序号
 */
const selectGroup = (idx: number) =>
  catchFn(async () => {
    if (curGroupIdx.value === idx) return

    curGroupIdx.value = idx
    searchKey.value = ''
    page = 1

    await updateFriend()
  })

/**
 * 搜索
 */
const search = () => catchFn(updateFriend)

/**
 * 新增/修改好友信息
 * @param friend 好友信息
 */
const editFriend = (friend?: T_Friend) => {
  let groupId = curGroupIdx.value > 0 ? curGroupIdx.value - 1 : -1

  if (friend) {
    const idx = groupList.value.findIndex(item => item.id === friend?.groupId)

    idx > 0 && (groupId = idx - 1)
  }

  curFriend.value = friend || {
    id: -1,
    nickname: '',
    gender: 0,
    birthday: '',
    zodiacSign: '',
    mbtiType: '',
    groupId,
    groupName: '',
    province: '',
    city: '',
    district: '',
  }
  curFriend.value.isNew = !friend

  uni.navigateTo({ url: '/pages/user/edit-info/index' })
}

/**
 * 修改本人信息
 */
const editSelf = () => {
  uni.navigateTo({ url: '/pages/user/edit-info/index' })
}

/**
 * 查看合盘报告好友信息
 */
const checkFriend = (type: number) => {
  const f = friends.value[curFriendIdx.value]

  if (!f) {
    topMessage.warn('请选择好友')

    return
  }

  uni.navigateTo({ url: `/pages/community/friend/report/info?type=${type}&friendId=${f.id}` })
}

/**
 * 还原状态
 */
const clear = () => {
  groupList.value = []
  curGroupIdx.value = -1
  friends.value = []
  curFriendIdx.value = -1
  searchKey.value = ''
  page = 1
}

export {
  updateFriend,
  init,
  newGroup,
  selectGroup,
  removeFriend,
  search,
  editFriend,
  editSelf,
  checkFriend,
  clear,
}
